<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人中心</title> 
    <link rel="stylesheet" href="./css/uCenter.css"> 
    <link rel="stylesheet" href="./css/table2.css"> 
    <link rel="stylesheet" href="./css/fileUpload.css">
    <link rel="stylesheet" href="./css/modal.css">
    
    <script src="./js/ajax.js"></script>
	<script src="./js/uri.js"></script>
	<script src="./js/template-web.js"></script> 
	<script src="./js/value.js"></script> 
    <script src="./js/replaceDiv.js"></script>	 
    <script src="./js/table.js"></script>
    <script src="./js/modal-face.js"></script>
    <script src="./js/click.js"></script>
</head> 

<script id="menuTemplate" type="text/html"> 
	<div class="menu-title" id="menuToggle">
	<span class="center-span">{{title}}<br>({{email}})</span>
	<span class="toggle-icon">《</span>
	</div>
	{{each menus m , index}}  
        <div class="menu-item" id="menu-{{index}}">
	       <div class="menu-text">
	          <i>{{m["icon"]}}</i>
	          <span>{{m["mitem"]}}</span>
	       </div>
	       <span class="arrow-icon">▶</span>
	    </div>
	   <ul class="submenu">
          {{each m["subs"] s , sIndex}}
             <li menu-url="{{s['url']}}" id="menu-{{index}}-{{si}}">{{s["sitem"]}}</li>
          {{/each}} 
	   </ul>
    {{/each}} 
	<div class="resize-handle" id="resizeHandle"></div>
</script>
    
<body>
    <!-- 顶部标题行 -->
    <div class="header">
        <div class="logo">
            <img src="img/logo.jpg" alt="公司Logo">
        </div>
        <div class="title" id="sys-title">百业榜工作桌面</div>
        <div>
           <button id="ui-lang" value="en" onClick="changeUILang()">English</button>&nbsp;
        </div>
        <div>
           <button id="exitButton" onClick="logout()">退出登录</button> 
        </div>
    </div>
    
    <!-- 主内容区 -->
    <div class="content">
        <!-- 左侧菜单区 -->
        <div class="menu-container" id="menuContainer"> 
           <!-- 替换为 template 内容 -->
        </div> 
        <!-- 右侧工作区 -->
        <div class="work-area" id="workArea">
            <div class="page-content" id="workPageContent">
                <h2>欢迎使用系统</h2>
                <p>请从左侧菜单选择功能</p>
            </div>
        </div>
    </div>

<script>
    var currentLang = "cn";
    
    function changeUILang(){
    	//debugger;
    	var lang = getInputValueById("ui-lang"); 
    	if(lang=="en"){
    		setInputValueById("ui-lang","cn");
    		document.getElementById("ui-lang").innerText = "简体中文";
    		document.getElementById("exitButton").innerText = " Logout ";  
    		document.getElementById("sys-title").innerText = "Desktop Of Baiye Top"; 
    	}else{
    		setInputValueById("ui-lang","en");
    		document.getElementById("ui-lang").innerText = "English";
    		document.getElementById("exitButton").innerText = "退出登录";  
    		document.getElementById("sys-title").innerText = "百业榜工作桌面"; 
    	}
    	currentLang = lang;
    	localStorage.setItem("lang", currentLang);
    	readMainMenu(); 
    }
    
    function logout(){
		 // debugger;
		  if(curUser == null){
			  showPage("index.html");
			  return;
		  }
		  var json={}; //如提供了密码，则修改密码
		  var token = curUser["token"];
		  ajaxPostJson(logout_uri , token , json , function(status,ret){
				  console.log("Status="+status);
				  console.log("logout Data="+JSON.stringify(ret,null,2)); 
				  if(ret.status==1){ 
					  curUser = null;
					  localStorage.removeItem("cuser"); 
					  //localStorage.clear();
					  showPage("index.html");
				  }else{
					 //  alert(JSON.stringify(ret,null,2));
					 //  localStorage.clear();
					  localStorage.removeItem("cuser"); 
					  showPage("index.html");
				  }
			  });
		  
	}
    
    function initMenuEvent(){
    	//debugger;
    	 
    	const menuContainer = document.getElementById('menuContainer');
        const menuToggle = document.getElementById('menuToggle'); 
        const menuItems = document.querySelectorAll('.menu-item');
        const submenuItems = document.querySelectorAll('.submenu li'); 
            
        // 存储原始宽度
        let originalWidth = menuContainer.offsetWidth;
            
        // 菜单折叠/展开功能
        menuToggle.addEventListener('click', function() {
            const isCollapsed = menuContainer.classList.toggle('collapsed');
                
            // 更新箭头方向
            const icon = this.querySelector('.toggle-icon');
            icon.textContent = isCollapsed ? '》' : '《';
                
            // 如果是展开状态，恢复原始宽度
            if (!isCollapsed && originalWidth) {
                menuContainer.style.width = originalWidth + 'px';
            }
                
            // 折叠时关闭所有二级菜单
            if (isCollapsed) {
                document.querySelectorAll('.menu-item.expanded').forEach(item => {
                    item.classList.remove('expanded');
                });
            }
        });
            
        // 一级菜单点击事件 - 展开/折叠二级菜单
        menuItems.forEach(item => {
            item.addEventListener('click', function() {
                // 如果菜单是折叠状态，只展开不折叠
               if (menuContainer.classList.contains('collapsed')) {
                    // 先关闭所有已展开的菜单
                    document.querySelectorAll('.menu-item.expanded').forEach(i => {
                        i.classList.remove('expanded');
                    });
                    // 展开当前菜单
                    this.classList.add('expanded');
                    return;
                }
              
                // 切换展开状态
                this.classList.toggle('expanded');
                    
                // 移除其他菜单的active状态
                menuItems.forEach(i => {
                    if (i !== this) {
                        i.classList.remove('active');
                        i.classList.remove('expanded');
                    }
                });
                    
                // 设置当前菜单active状态
                this.classList.add('active');
            });
        });
            
        // 二级菜单项点击事件
        submenuItems.forEach(item => {
            item.addEventListener('click', function() {
                // 移除所有active类
                submenuItems.forEach(i => i.classList.remove('active'));
                // 给当前项添加active类
                this.classList.add('active');
                
                // 加载对应页面内容
                const url = this.getAttribute("menu-url");
                loadPage(url);
                
                var sid = this.getAttribute('id');
                noneSelectMain(sid);  //主菜单 不深色显示
                
                // 如果是折叠状态，点击后自动展开菜单
                if (menuContainer.classList.contains('collapsed')) {
                    menuContainer.classList.remove('collapsed');
                    menuToggle.querySelector('.toggle-icon').textContent = '❮';
                    
                }
            });
        });  
            
        // 默认展开第一个菜单
        if (!menuContainer.classList.contains('collapsed')) {
            menuItems[0].classList.add('expanded');
            //var sid = menuItems[0].getAttribute('id');
            //noneSelectMain(sid);  //主菜单 不深色显示
        }
    	
    }
    
    function noneSelectMain(sid){
    	var parts = sid.split('-'); // ["menu", "1", "2"]
        var mid = parts.slice(0, 2).join('-'); // "menu-1"
        var mm = document.getElementById(mid);
        mm.classList.remove('active');   //主菜单的 深色显示 不显示
    } 
    
    function initResize(){
    	 
            const resizeHandle = document.getElementById('resizeHandle');  
          
            // 菜单宽度调整功能
            let isResizing = false;
            let lastDownX = 0;
            
            resizeHandle.addEventListener('mousedown', function(e) {
                // 如果当前是折叠状态，先展开
                if (menuContainer.classList.contains('collapsed')) {
                    menuContainer.classList.remove('collapsed');
                    menuToggle.querySelector('.toggle-icon').textContent = '❮';
                }
                
                isResizing = true;
                lastDownX = e.clientX;
                originalWidth = menuContainer.offsetWidth; // 更新原始宽度
                document.body.style.cursor = 'col-resize';
                document.addEventListener('mousemove', handleMouseMove);
                document.addEventListener('mouseup', handleMouseUp);
                e.preventDefault();
            });
            
            function handleMouseMove(e) {
                if (!isResizing) return;
                
                const newWidth = e.clientX - menuContainer.offsetLeft;
                
                // 设置最小和最大宽度
                if (newWidth > 150 && newWidth < 500) {
                    menuContainer.style.width = newWidth + 'px';
                    originalWidth = newWidth; // 更新原始宽度
                }
            }
            
            function handleMouseUp() {
                isResizing = false;
                document.body.style.cursor = '';
                document.removeEventListener('mousemove', handleMouseMove);
                document.removeEventListener('mouseup', handleMouseUp);
            } 
    }
    
    function loadPage(url) { 
    	debugger; 
        ajaxGetText(url+"?" + Date.now(), function(code,content){
        	   if(code==0){
        		   //pageContent.innerHTML = content;
        		   //content="<h2>"+url+"</h2>"+content;
        		   console.log("load url:"+url);
        		   console.log("Html:"+content);
        		   //replaceDivContentWithScriptsEnhanced("workPageContent",content); 
        		   replaceContentWithResources("workPageContent",content);
        		   //replaceDivContent('workPageContent', content);
        	   }else{
        		   alert("Error!\r\n"+content);
        	   }
        	},
        	prefix=false,
        	token=null
        ); 
    }
    
    function showMenu(me){
    	debugger;
    	var json={};
        json["title"] = me["title"]; 
        json["menus"] = me["menus"]; 
        json["email"]  = curUser["email"];
        
        var html = template('menuTemplate', json);   
        console.log(html);
    	document.getElementById('menuContainer').innerHTML = html; 
    	initMenuEvent();
    	initResize();
    	switchContantLang();
    }
    
    function switchContantLang(){
    	//alert("to lang:"+uLang);
    }
    
    
    function readMainMenu(){ 
    	 
    	var url = "./json/menu-"+curUser["utype"]+"-"+currentLang+".json?" + Date.now() ; 
    	
    	//var lang = getInputValue("uiLang");
    	
    	ajaxGetJson(url,function(status,res){
    		if(status==0){ 
    			showMenu(res);
    		}else{
    			alert("Error!");
    		}
    		//alert("status="+status+"\r\nText="+JSON.stringify(res));
    	}); 
    }
    
    function repeatBeat() {
    	ajaxPostJson(user_beat_uri,curUser["token"],{},function(status,res){
    		if(status != 0){ 
    			alert("Error!");
    		} 
    		setTimeout(repeatBeat, 1000*900); // 16分钟后再次执行
    	});  
    }
    
    readMainMenu(); 
    repeatBeat();
</script>
</body>
</html>